/** 
 * Copyright (C), 2010-2012, AIYOU Software Co.,Ltd. ALL RIGHTS RESERVED. 
 * File name:TietiaoUtil.java
 * Version:1.0
 * Date:Dec 17, 2011
 * Description: 
 * author:whh 
 */
package com.tietiao.common.util;

import java.util.List;
import java.util.Random;
import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.tietiao.common.constants.TietiaoConstants;
import com.tietiao.dao.model.SysUser;
import com.tietiao.service.sysuser.SysUserService;

public class TietiaoUtil {

	public static String SESSION_USER = "sysUserSession";

	public static String TOKEN_KEY = "_TOKEN_KEY";

	public static String RANDOM_KEY = "_RANDOM_KEY";
	
	public static String COOKIE_USER_NAME = "_COOKIE_USER_NAME";
	
	public static String COOKIE_USER_PASSWORD= "_COOKIE_USER_PASSWORD";
	
	public static String PHOTO_ROOT_PATH = "photoPath";
	
	private static final char[] AllChar =("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz").toCharArray();
	public static SysUserService sysUserService = null;
	/**
	 * 功能：获得当前登陆的用户信息
	 * 
	 * @author: whh
	 * @Date: Dec 17, 2011
	 * @return
	 */
	public static SysUser getSessionUser(HttpServletRequest request) {
		Object obj = request.getSession().getAttribute(SESSION_USER);
		if (obj == null) {
			return null;
		} else {
			return (SysUser) obj;
		}
	}
	
	/**
	 * 功能：保存用户信息至session
	 */
	public static void setSessionUser(HttpServletRequest request,SysUser user){
		request.getSession().setAttribute(SESSION_USER,user);
	}
	
	public static String getRandom(HttpServletRequest request) {
		Object obj = request.getSession().getAttribute(RANDOM_KEY);
		if (obj == null) {
			return null;
		} else {
			return obj.toString();
		}
	}
	
	/**
	 * 功能：设置图片服务器路径
	 * @author: whh 
	 * @Date: 2011-12-26
	 * @param request
	 */
	public static void setRootPath(HttpServletRequest request){
		request.getSession().setAttribute(PHOTO_ROOT_PATH, TietiaoConstants.SERVICE_ROOT_PATH);
	}
	/**
	 * 功能：设置Token
	 * 
	 * @return
	 */
	public static void setToken(HttpServletRequest request) {
		if (request != null) {
			request.getSession().setAttribute(TOKEN_KEY,UUID.randomUUID().toString());
		}
	}

	/**
	 * 
	 * 功能：页面获取token输入信息
	 * 
	 * @author: whh
	 * @Date: Dec 18, 2011
	 * 
	 * @return
	 */
	public static String tokenInput() {
		HttpServletRequest request = ServletActionContext.getRequest();
		Object obj = request.getSession().getAttribute(TOKEN_KEY);
		if (obj == null) {
			return "<input name='token_name_page' value='' type='hidden'/>";
		} else {
			return "<input name='token_name_page' value='" + obj.toString()+ "' type='hidden'/>";
		}
	}

	/**
	 * 
	 * 功能：判断是否是新提交。
	 * 
	 * @author: whh
	 * @return
	 */
	public static boolean isToken(HttpServletRequest request) {
		Object obj = request.getSession().getAttribute(TOKEN_KEY);
		String str = request.getParameter("token_name_page");
		if (obj == null) {
			return false;
		} else if (str == null) {
			return false;
		} else {
			request.getSession().removeAttribute(TOKEN_KEY);
			return obj.toString().equals(str);
		}
	}
	/**
	 * 获得邀请码
	 * @return
	 */
	public static String getInviteCode(){
		StringBuffer code = new StringBuffer();
		for (int i = 0; i <6; i++) {
			code.append(AllChar[new Random().nextInt(52)]);
		}
		return code.toString();
	}
	/**
	 * 
	 * 功能：当前登陆用户和传入用户的关系 0：无关系 1：登陆用户本身 2:登陆用户关注好友 3：好友关注用户：4：两人相互关注
	 * @author: whh 
	 * @Date: 2012-1-8
	 * @return
	 */
	public static Integer getAttent(Integer userId,List<String> list){
		if(list==null){
			return 0;
		}else{
			HttpServletRequest request = ServletActionContext.getRequest();
			SysUser user = getSessionUser(request);
			if(user==null || userId==user.getUserId()){
				return 1;
			}else{
				boolean attenMe= list.get(0).contains(","+userId+",");
				boolean meAtten= list.get(1).contains(","+userId+",");
				if(attenMe && meAtten){
					return 4;
				}else if(attenMe){
					return 3;
				}else if(meAtten){
					return 2;
				}else{
					return 0;
				}
			}
		}
	}
	
	/**
	 * 查cookies是否有值
	 * @param req
	 */
	public static boolean cookiesLogin(HttpServletRequest req,HttpServletResponse response) {
		String userName = getStrByCookies(req,COOKIE_USER_NAME);
		String password = getStrByCookies(req, COOKIE_USER_PASSWORD);
		if(!StringUtil.strIsNull(password) && !StringUtil.strIsNull(userName)){
			
			if(sysUserService==null){
				sysUserService = (SysUserService)BeanFactory.getBean("sysUserServiceImp");
			}
			SysUser sysUser = sysUserService.loadSysUserByCodeOrEmail(userName);
			if(sysUser!=null && password.equals(sysUser.getPassword())){
				req.getSession().setAttribute(SESSION_USER, sysUser);
			}else{
				Cookie cookie = new Cookie("sitepass","");//如果登陆失败
				cookie.setPath("/");
				cookie.setMaxAge(2592000);//过期时间
				response.addCookie(cookie);
			}
		}
		return false;
	}
	
	/**
	 * 查cookies是否有值
	 * @param req
	 */
	public static String getStrByCookies(HttpServletRequest req,String key) {
		Cookie[] cookies = req.getCookies();
		for (int i = 0; cookies!=null && i < cookies.length; i++) {
			Cookie cookie = cookies[i];
			if(key.equals(cookie.getName())){
				return  StringUtil.decode(cookie.getValue());
			}
		}
		return "";
	}
	
	/**
	 * 在客户端加入cookie
	 */
	public static void setCookies(HttpServletResponse response, String userName,String password) {
		Cookie cookie = null;
		if(userName!=null){
			cookie = new Cookie(COOKIE_USER_NAME,StringUtil.encode(userName)); //用户名
			cookie.setPath("/");
			cookie.setMaxAge(2592000);//过期时间
			response.addCookie(cookie);
		}
		
		if(StringUtil.strIsNull(password)){
			cookie = new Cookie(COOKIE_USER_PASSWORD,"");
		}else{
			cookie = new Cookie(COOKIE_USER_PASSWORD,password);
		}
		cookie.setPath("/");
		cookie.setMaxAge(2592000);//过期时间
		response.addCookie(cookie);
	}
	
}
